package com.woniuxy.meal.controller;


import com.woniuxy.meal.common.Result;
import com.woniuxy.meal.entity.DietOrder;
import com.woniuxy.meal.form.AddOrderForm;
import com.woniuxy.meal.service.DietOrderService;
import com.woniuxy.meal.service.dto.OrderInfoDto;
import com.woniuxy.meal.util.RedisUtil;
import com.woniuxy.meal.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 外卖订单 前端控制器
 * </p>
 *
 * @author zz
 * @since 2023年06月12日
 */
@RestController
@RequestMapping("/dietOrder")
@Api(tags = "订单相关业务")
public class DietOrderController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DietOrderService dietOrderService;

    @ApiOperation("生成订单接口")
    @PostMapping("/addOrder")
    public Result addOrder(@Valid  @RequestBody AddOrderForm adf, @RequestHeader String token) throws Exception {
        Long userId = redisUtil.getUserIdByToken(token);
        System.out.println(adf);
        OrderInfoDto orderInfoDto = dietOrderService.addOrder(adf,userId);
        return Result.success(200,"新增订单成功",orderInfoDto);
    }

    @ApiOperation("取消订单接口")
    @GetMapping("/cancelOrder")
    public Result cancelOrder(String orderNum, @RequestHeader String token) throws Exception{
        Long userId = redisUtil.getUserIdByToken(token);
        dietOrderService.cancelOrder(orderNum,userId);
        return Result.success(200,"取消订单成功",null);
    }


    @ApiOperation("展示当前用户所有订单接口")
    @GetMapping("/showUserOrder")
    public Result showUserOrder(@Valid  @RequestHeader String token) throws Exception{
        Long userId = redisUtil.getUserIdByToken(token);
        List<OrderInfoDto> list = dietOrderService.showOrderByUserId(userId);
        return Result.success(200,"展示当前所有用户订单成功",list);
    }





    @GetMapping("/pay/{num}")
    @ApiOperation("支付接口")
    public void payOrder(@PathVariable("num") String num ) throws Exception{
//        System.out.println("vvvvvv"+num);

        String result =  dietOrderService.payOrder(num);
        HttpServletResponse response = WebUtil.getResponse();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        response.getWriter().write(result);
        response.flushBuffer();
    }

    @PostMapping("/payCallback")
    @ApiOperation("支付回调")
    public void payCallback() throws Exception{

        String trade_status = WebUtil.getRequest().getParameter("trade_status");
        if (trade_status.equals("TRADE_SUCCESS")){
            String orderId = WebUtil.getRequest().getParameter("out_trade_no");
            DietOrder orderInfo = dietOrderService.getById(orderId);
            dietOrderService.payCallback(orderInfo);
        }

    }


}

